import { ElMessage, ElMessageBox } from 'element-plus';
import type { ElMessageBoxOptions } from 'element-plus';
import { InfoCircleFilled, CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons-vue';

import { useI18n } from './useI18n';
import { Icon } from '/@/components/Icon'

export declare type IconType = 'success' | 'info' | 'error' | 'warning';

function getIcon(iconType: string) {
  if (iconType === 'warning') {
    return <InfoCircleFilled class="modal-icon-warning" />;
  } else if (iconType === 'success') {
    return <CheckCircleFilled class="modal-icon-success" />;
  } else if (iconType === 'info') {
    return <InfoCircleFilled class="modal-icon-info" />;
  } else if (iconType === 'loading') {
    return <Icon icon='eos-icons:loading'/>;
  } else {
    return <CloseCircleFilled class="modal-icon-error" />;
  }
}

/**
 * @description: Create confirmation box
 */
function createConfirm(options: Partial<ElMessageBoxOptions> & {onOk: {(): void}}): any {
  const { t } = useI18n();
  return ElMessageBox.confirm(options.message, options.title, {
    confirmButtonText: t('common.okText'),
    cancelButtonText: t('common.cancelText'),
    type: 'warning'
  }).then(() => {
    options.onOk()
  })
}

function createSuccessModal(options: Partial<ElMessageBoxOptions>) {
  const { t } = useI18n();
  return ElMessageBox({ 
    type: 'success',
    confirmButtonText: t('common.okText'),
    ...options,
  })
}

function createErrorModal(options: Partial<ElMessageBoxOptions>) {
  const { t } = useI18n();
  return ElMessageBox({ 
    type: 'error',
    confirmButtonText: t('common.okText'),
    ...options,
  })
}

function createInfoModal(options: Partial<ElMessageBoxOptions>) {
  const { t } = useI18n();
  return ElMessageBox({ 
    type: 'info',
    confirmButtonText: t('common.okText'),
    ...options,
  })
}

function createWarningModal(options: Partial<ElMessageBoxOptions>) {
  const { t } = useI18n();
  return ElMessageBox({ 
    type: 'warning',
    confirmButtonText: t('common.okText'),
    ...options,
  })
}

/**
 * @description: message
 */
interface IElessage {
  message: string,
  type?: 'success'|'info'|'warning'|'error'|'loading',
  grouping?: boolean,
  showClose?: boolean,
  duration?: number,
}
export function useMessage() {
  return {
    createMessage: ({message, type = 'success', grouping = true, showClose = false, duration = 3000}: IElessage) => {
      let options = Object.assign({
        showClose: showClose,
        message: message,
        type: type == 'loading' ? null : type,
        icon: type == 'loading' ? getIcon('loading') : null,
        grouping: grouping,
        duration: duration,
      })
      ElMessage(options)
    },
    createConfirm: createConfirm,
    createSuccessModal,
    createErrorModal,
    createInfoModal,
    createWarningModal,
  };
}
